﻿using Kernel.Core.IService;
using Kernel.Core.Models.Settings;
using Kernel.Core.Service;
using Kernel.IService.Repository.Demo;
using Kernel.Model.Demo;

namespace WebAPI.Areas.Demo.Controllers
{
    /// <summary>
    /// FreeSql功能演示
    /// </summary>
    [ApiVersion("1.0")]
    public class TopicController : DemoBaseController
    {
        public ITopicRepository TopicRepo { get; set; }

        public TopicController()
        {

        }

        /// <summary>
        /// 添加文章信息
        /// </summary>
        /// <returns>返回文章信息</returns>
        [HttpPost]
        [Route("topic"), MapToApiVersion("1.0")]
        public async Task<IActionResult> AddTopic_V1_0([FromForm] Topic topic)
        {
            var items = new List<Topic>();
            for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });

            var i = await TopicRepo.AddTopic_V1_0(items);
            var result = new CommandResult<int> { Data = i };

            return Ok(result);
        }

        /// <summary>
        /// 缓存测试
        /// </summary>
        /// <returns>返回文章信息</returns>
        [HttpPost]
        [Route("cache"), MapToApiVersion("1.0")]
        public async Task<IActionResult> TestCache_V1_0()
        {
            var items = new List<Topic>();
            for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });

            ICacheService cacheSvc = ServiceHost.Current.GetService<ICacheService<KernelCacheFlag>>();

            //添加缓存
            cacheSvc.Set("key1", 1234);
            cacheSvc.Set("key2", new List<string> { "aa", "bb" });
            cacheSvc.Set("key3", items);
            cacheSvc.Set("key4", new { Name = "张三", Birthday = DateTime.Now});

            //读取缓存
            var value1 = cacheSvc.Get<int?>("key1");
            var value2 = cacheSvc.Get<List<string>>("key2");
            var value3 = cacheSvc.Get<List<Topic>>("key3");
            var value4 = cacheSvc.Get<object>("key4");

            //移除缓存
            cacheSvc.Remove("key1");
            value1 = cacheSvc.Get<int?>("key1");
            cacheSvc.RemoveAll(new List<string> { "key2", "key3", "key4" });
            value2 = cacheSvc.Get<List<string>>("key2");
            value3 = cacheSvc.Get<List<Topic>>("key3");
            value4 = cacheSvc.Get<object>("key4");

            //绝对过期
            cacheSvc.Set("key1", 1234, TimeSpan.FromSeconds(30));
            value1 = cacheSvc.Get<int?>("key1");

            //滑动过期
            cacheSvc.Set("key1", 1234, TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(60));
            value1 = cacheSvc.Get<int?>("key1");

            return Ok(value1);
        }

    }
}
